package main

import (
	"flag"
	"fmt"
	"log"
	//	"math"
	"os"
	//	"strconv"
	//	"strings"
	"time"
	//	"github.com/robvanmieghem/go-opencl/cl"
)

//Version is the released version string of gominer
var Version = "0.5-Dev"

const maxUint = ^uint(0)
const maxInt = int(maxUint >> 1)

type MiningWork struct {
	Target []byte
	Header []byte
}

func mining(siad *SiadClient, miningWorkChannel chan *MiningWork, mingingWorkReqChan chan chan *MiningWork,
	submitChan chan *[]byte, fechHeaderTimer *time.Timer) {
	for {
		select {
		case <-fechHeaderTimer.C:
			target, header, err := siad.GetHeaderForWork()

			if err != nil {
				log.Println("ERROR fetching work -", err)
			} else {
				miningWorkChannel <- &MiningWork{Target: target, Header: header}
			}
		case mwc := <-mingingWorkReqChan:
			target, header, err := siad.GetHeaderForWork()

			if err != nil {
				log.Println("ERROR fetching work -", err)
				mwc <- nil
			} else {
				mwc <- &MiningWork{Target: target, Header: header}
			}
		case newHeader := <-submitChan:
			err := siad.SubmitHeader(*newHeader)
			if err != nil {
				log.Println("ERROR submit work -", err)
			}
		}
	}
}

func main() {
	printVersion := flag.Bool("v", false, "Show version and exit")
	//	useCPU := flag.Bool("cpu", false, "If set, also use the CPU for mining, only GPU's are used by default")
	//	flag.IntVar(&intensity, "I", intensity, "Intensity")
	siadHost := flag.String("H", ":7777", "siad host and port")
	secondsOfWorkPerRequestedHeader := flag.Int("S", 10, "Time between calls to siad")
	//	excludedGPUs := flag.String("E", "", "Exclude GPU's: comma separated list of devicenumbers")
	queryString := flag.String("Q", "", "Query string")
	flag.Parse()

	if *printVersion {
		fmt.Println("gominer version", Version)
		os.Exit(0)
	}

	siad := NewSiadClient(*siadHost, *queryString)

	//Start fetching work
	workChannel := make(chan *MiningWork, 10)
	workReqChannel := make(chan chan *MiningWork, 10)
	fetchHeaderTimer := time.NewTimer(time.Duration(*secondsOfWorkPerRequestedHeader) * time.Second)
	submitChan := make(chan *[]byte, 10)
	go mining(siad, workChannel, workReqChannel, submitChan, fetchHeaderTimer)

	stratumCfg := &StratumCfg{Enabled: true, Listen: *siadHost, Timeout: "10s", MaxConn: 100}
	stratumServer := NewStratumServer(stratumCfg, workChannel, workReqChannel, submitChan)
	stratumServer.start()

}
